package com.company.test.sync;

import sun.misc.Unsafe;

public class DEF1 {
    volatile int state = 0;
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    public static  long stateOffset;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset
                    (DEF1.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }


    public void lock() {
        for (; ; ) {
            if (compareAndSet(0, 1)){
                break;
            }
        }
    }

    public void unlock(){
        state = 0;
    }

    public Boolean compareAndSet(int expect, int newValue) {
        return unsafe.compareAndSwapInt(this, stateOffset, expect, newValue);
    }

    public static void main(String[] args) {
        DEF1 def1 = new DEF1();
        def1.lock();
        System.out.println("***********************");
        def1.unlock();
    }

}
